<template>
  <j-modal :title="title" :width="width" :visible="visible" :confirmLoading="confirmLoading" :maskClosable="false"
    :keyboard="false" :forceRender="true" switchFullscreen @cancel="handleCancel" wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{ $t('inPrint.cancel') }}</a-button>
      <a-button type="primary" @click="handleOk" :disabled="confirmLoading">{{ $t('commodityManagement.preservation') }}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" ref="form">
        <a-row class="form-row" :gutter="24">
          <!-- 运输公司 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('purchasingManagement.TransportCompany')">
              <a-select :placeholder="$t('purchasingManagement.selectTransportCompany')"
                v-decorator="['transportId', validatorRules.transportId]" :dropdownMatchSelectWidth="false"
              >
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <!-- <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()"
                    @click="addSupplier"><a-icon type="plus" /> {{ $t('popup.newSupplier') }}</div> -->
                </div>
                <a-select-option v-for="item in transportList" :key="item.id" :value="item.id">
                  {{ item.transpotName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--操作员 -->
          <!-- <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')">
              <a-select :placeholder="$t('financialManagement.selectPersonnel')"
                v-decorator.trim="['handsPersonId', validatorRules.handsPersonId]" :dropdownMatchSelectWidth="false"
                showSearch optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()"
                    @click="addPerson"><a-icon type="plus" /> {{ $t('popup.newHandler') }}</div>
                </div>
                <a-select-option v-for="(item, index) in personList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')"
              data-step="3" :data-title="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator.trim="['creator']" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator="[ 'tenantId']" :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator="[ 'custom5']" :readOnly="true" />
            </a-form-item>
          </a-col>
          <!-- 单据日期 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['billTime', validatorRules.billTime]" :show-time="true" />
            </a-form-item>
          </a-col>
          <!-- 单据编号 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="['billNo',validatorRules.billNo]" disabled
              :readOnly="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <!-- 操作按钮 -->
            <div class="action-button">
              <a-button type="primary" icon="plus" @click="handleClickAdd">{{ $t('setailManagement.newlyAdded')
              }}</a-button>
              <span class="gap"></span>
              <a-button type="primary" icon="minus" @click="handleClear">{{ $t('popup.empty') }}</a-button>
            </div>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="24">
            <j-editable-table :ref="refKeys[0]" :loading="accountTable.loading" :columns="accountTable.columns"
              :dataSource="accountTable.dataSource" :maxHeight="300" :rowNumber="false" :rowSelection="false"
              :actionButton="false" @valueChange="onValueChange">
              <template #delete="record">
                <div style="text-align: center;">
                  <a-popconfirm :title="$t('manuManagement.areDelete')"
                    @confirm="() => removeRows(record)">
                    <a-icon type="delete"></a-icon>
                  </a-popconfirm>
                </div>
              </template>
              <template #rowIndex="record">
                <div style="text-align: center;">{{ record.index + 1 }}</div>
              </template>
          </j-editable-table>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" label="">
              <a-textarea :rows="2" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="['remark']"
                style="margin-top:8px;" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
              :label="$t('financialManagement.paymentAccount')">
              <a-select :placeholder="$t('financialManagement.selectPayment')"
                v-decorator="['accountId', validatorRules.accountId]" :dropdownMatchSelectWidth="false" showSearch
                optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()"
                    @click="addAccount"><a-icon type="plus" /> {{ $t('popup.newAccount') }}</div>
                </div>
                <a-select-option v-for="(item, index) in accountList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.totalPayment')"
              >
              <a-input :placeholder="$t('popup.pleaseTotalPayment')" v-decorator.trim="['totalPrice']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
              :label="$t('financialManagement.preferentialAmount')">
              <a-input :placeholder="$t('popup.pleaseDiscountAmount')"
                v-decorator.trim="['discountMoney', validatorRules.discountMoney]" @keyup="onKeyUpDiscountMoney" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.actualPayment')">
              <a-input :placeholder="$t('popup.pleaseActualPayment')" v-decorator.trim="['changeAmount']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.enclosure')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="financial"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <debt-bill-list ref="debtBillList" @ok="debtBillListOk"></debt-bill-list>
    <vendor-modal ref="vendorModalForm" @ok="vendorModalFormOk"></vendor-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <person-modal ref="personModalForm" @ok="personModalFormOk"></person-modal>
    <link-freight-payment-list ref="linkFreightPayment" @ok="linkFreightPaymentModalOk"></link-freight-payment-list>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import DebtBillList from '../dialog/DebtBillList'
import VendorModal from '../../system/modules/VendorModal'
import AccountModal from '../../system/modules/AccountModal'
import PersonModal from '../../system/modules/PersonModal'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { FinancialModalMixin } from '../mixins/FinancialModalMixin'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import LinkFreightPaymentList from '../dialog/LinkFreightPaymentList.vue'
import { gettTransportAllList } from '@/api/api'
export default {
  name: "FreightPaymentModal",
  mixins: [JEditableTableMixin, FinancialModalMixin],
  components: {
    DebtBillList,
    VendorModal,
    AccountModal,
    PersonModal,
    JUpload,
    JDate,
    LinkFreightPaymentList,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    }
  },
  data() {
    return {
      title: this.$t('setailManagement.operation'),
      width: '1600px',
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 0,
      visible: false,
      model: {},
      fileList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      refKeys: ['accountDataTable',],
      activeKey: 'accountDataTable',
      accountTable: {
        loading: false,
        dataSource: [],
        columns: [
        { title: this.$t('defaultTranslate.lineNumber'), key: 'rowIndex', width: '4%', type: 'slot' },
        { title: this.$t('commodityManagement.delete'), width: '3%', key: 'delete', type: 'slot' },
        { title: this.$t('setailManagement.documentDate'),dataIndex: 'billTimeStr', key: 'billTimeStr', width: '15%', readonly: true },
        { title: this.$t('purchasingManagement.TransportCompany'),dataIndex: 'transpotName', key: 'transpotName', width: '20%', readonly: true },
        { title: this.$t('purchasingManagement.trackingNumber'),dataIndex: 'billNo', key: 'billNo', width: '20%', readonly: true },
        { title: this.$t('manuManagement.purchaseOrder'),dataIndex: 'number', key: 'number', width: '20%'},
        { title: this.$t('purchasingManagement.totalAmount'),dataIndex: 'eachAmount',  key: 'eachAmount', width: '15%',
          validateRules: [{ required: true}]
        }, 
        ]
      },
      confirmLoading: false,
      validatorRules: {
        organId: {
          rules: [{ required: true, message: this.$t('popup.pleaseSupplier') + '!' }]
        },
        accountId: {
          rules: [{ required: true, message: this.$t('financialManagement.selectPayment') + '!' }]
        },
        billTime: {
          rules: [{ required: true, message: this.$t('popup.pleaseSelectDocumentDate') + '!' }]
        },
        accountIorganId: {
          rules: [{ required: true, message: this.$t('popup.pleaseSupplier') + '!' }]
        },d: {
          rules: [{ required: true, message: this.$t('popup.pleaseSelectPaymentAccount') + '!' }]
        },
        discountMoney: {
          rules: [{ required: true, message: this.$t('popup.pleaseDiscountAmount') + '!' }]
        },
        changeAmount: {
          rules: [{ required: true, message: this.$t('popup.pleaseCollectionAmount') + '!' }]
        },
        transportId: {
          rules: [{ required: true, message: this.$t('popup.pleaseSelectTransportCompany') + '!' }]
        },
          billNo:{
            rules: [
              { required: true, message: this.$t('otherJS.DocumentNoFailure') }
            ]
          },
        currentType: {}
      },
      url: {
        add: '/accountHead/addAccountHeadAndDetail',
        edit: '/accountHead/updateAccountHeadAndDetail',
        detailList: '/accountItem/getDetailList'
      },
      transportList: []
    }
  },
  watch: {
    'accountTable.dataSource' () {
      let price
      if (!this.accountTable.dataSource.length) {
        price = 0
        this.form.setFieldsValue({'discountMoney':price })
      } else  {
        if (this.accountTable.dataSource.length === 1) {
          price = this.accountTable.dataSource[0].eachAmount
        } else {
          price = this.accountTable.dataSource.reduce((pre, cur) => {
            return (pre.eachAmount*100 + cur.eachAmount*100) / 100
          })
        }
      }
      if (Number(this.form.getFieldValue('discountMoney')) === 0) {
        this.form.setFieldsValue({'changeAmount':price })
      }
      this.form.setFieldsValue({'totalPrice':price })
    }
  },
  created() {
    this.$nextTick(() => {
      this.form.setFieldsValue({ 'userName': this.getLocalStorage('pro__Login_Userinfo').username })
    })
  },
  methods: {
    initTransport () {
      gettTransportAllList().then(res => {
        this.transportList = res.data
      })
    },
    // onSearchLinkNumber() {
    //   let organId = this.form.getFieldValue('organId')
    //   this.$refs.linkBillList.show('', this.$t('manuManagement.purchaseOrder'), this.$t('warehouseManagement.supplier'), "2", organId, this.$t('purchasingManagement.purchaseOrder'))
    //   this.$refs.linkBillList.title = this.$t('popup.selectPurchaseOrder')
    // },
    //调用完edit()方法之后会自动调用此方法
    editAfter() {
      this.currentType = this.$listeners.getCurrentType(this.$route.path)
      this.billStatus = '0'
      if (this.action === 'add') {
        this.fileList = []
      } else {
        this.model.billTime = this.model.billTimeStr
        // this.model.userName = this.model.billTimeStr
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'organId', 'handsPersonId', 'billTime', 'billNo', 'remark','tenantId','custom5',
            'accountId', 'totalPrice', 'discountMoney', 'changeAmount', 'userName', 'creator'))
        });
        
        // 加载子表数据
        let params = {
          headerId: this.model.id
        }
        let url = this.readOnly ? this.url.detailList : this.url.detailList;
        this.requestSubTableData(url, params, this.accountTable);
      }
      this.initSupplier()
      this.initPerson()
      this.initAccount()
      this.initTransport()
      this.addInit(this.currentType.prefix)
    },
    linkFreightPaymentModalOk (data) {
      this.accountTable.dataSource = []
      this.accountTable.dataSource.push(data)
      this.$nextTick(()=>{
        this.form.setFieldsValue({
          'tenantId':data.tenantId,
          'custom5':data.custom5
        })
      })
    },
    //提交单据时整理成formData
    classifyIntoFormData(allValues) {
      let totalPrice = 0
      let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values
      billMain.type = this.currentType.type
      for (let item of detailArr) {
        totalPrice += item.eachAmount - 0
      }
      
      const hd = function (item) {
        key1s.forEach((key, index) => {
          item[key1s[index]] = item[key2s[index]]
          delete item[key2s[index]]
        })
      }
      billMain.custom3 = billMain.transportId
      delete billMain.transportId
      billMain.creator = this.$ls.get('Login_Userinfo').id
      const key1s = ['receiveTime', 'billNo', 'number']
      const key2s = ['billTimeStr', 'custom4', 'custom5']
      for (let i = 0; i < detailArr.length; i++) {
        hd(detailArr[i])
        
        detailArr[i].custom1 = this.accountTable.dataSource[i].billId
        detailArr[i].custom5 = this.accountTable.dataSource[i].custom5
        detailArr[i].tenantId = this.accountTable.dataSource[i].tenantId
        console.log(detailArr[i],'hu')
      }
      console.log(billMain,detailArr, 335)
      billMain.totalPrice = 0 - totalPrice
      billMain.changeAmount = 0 - billMain.changeAmount
      // if(this.fileList && this.fileList.length > 0) {
      //   billMain.fileName = this.fileList
      // }
      if (this.model.id) {
        billMain.id = this.model.id
      }
      billMain.status = this.billStatus
      let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
      return {
        info: JSON.stringify(billMain),
        attachment: fileList,
        rows: JSON.stringify(detailArr),
      }
    },
    handleClickAdd() {
      let transportId = this.form.getFieldValue('transportId')
      if (!transportId) {
        this.$message.error(this.$t('popup.pleaseSelectTransportCompany') + '!')
        return
      }
      let type = ''
      if (this.currentType.prefix === 'ZFYSFK') {
        type = '直发运费'
      } else {
        type = '运费'
      }
      this.$refs.linkFreightPayment.open(transportId, type)
    },
    handleClear() {
      this.accountTable.dataSource = []
    },
    removeRows (text) {
      this.$refs[this.refKeys[0]].removeRows(text.rowId)
    }
  }
}
</script>
<style scoped>
.action-button {
  margin-bottom: 8px;
}

.gap {
  padding-left: 8px;
}
</style>

<style scoped lang="less">
::v-deep .ant-spin-container .thead {
  background: #beddf9;
  & > .tr > .td {
    border-left: 1px solid #f2f2f2;
    text-align: center;
  }
}
</style>